package com.lucifer.d.security.util;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author Lucifer
 * @create 2023 - 03 - 04 10:18
 */
public class ReflectUtil {

    /**
     * set方法获取
     *
     * @param fieldName
     * @return
     */
    public static String setMethod(String fieldName){
        return "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    }

    /**
     * get方法获取
     *
     * @param fieldName
     * @return
     */
    public static String getMethod(String fieldName){
        return "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    }

    /**
     * 反射获取对象属性（注解）
     *
     * @return
     */
    public static Object getObjFieldOnReflect(Object obj, Class annotationClass) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class objClass = obj.getClass();
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields){
            if (field.getAnnotation(annotationClass) != null){
                return objClass.getDeclaredMethod(getMethod(field.getName())).invoke(obj);
            }
        }
        return null;
    }

    /**
     * 反射摄入对象属性（仅字符串）（注解）
     *
     * @return
     */
    public static void setValueOnReflect(Object obj, Class annotationClass, String value) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class objClass = obj.getClass();
        Field[] fields = objClass.getDeclaredFields();
        for (Field field : fields){
            if (field.getAnnotation(annotationClass) != null){
                objClass.getDeclaredMethod(setMethod(field.getName()), String.class).invoke(obj, value);
            }
        }
    }

}
